﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;

namespace Amitabha
{
    /// <summary>
    /// 阿弥陀佛中间件
    /// </summary>
    public class AmitabhaMiddleware
    {
        // 中间必备依赖
        private readonly RequestDelegate _next;
        private readonly AmitabhaOptions _options;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next">请求委托</param>
        /// <param name="options">选项</param>
        public AmitabhaMiddleware(RequestDelegate next, IOptions<AmitabhaOptions> options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            // 可用 ?? 合并运算符简写上面的代码
            // 简写代码如下:
            //_next = next ?? throw new ArgumentNullException(nameof(next));

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next = next;
            _options = options.Value;
        }

        /// <summary>
        /// 中间件必备方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
            if (!_options.Path.HasValue || _options.Path == context.Request.Path)
            {
                return context.Response.WriteAsync(Fo.Lai());
            }
            return _next(context);
        }
    }
}
